package top.jolyoulu.modules.poimodule.excel.reader;

import lombok.extern.slf4j.Slf4j;
import top.jolyoulu.corecommon.utils.other.DateUtils;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: JolyouLu
 * @Date: 2023/12/17 16:46
 * @Description 处理每一个单元格的Handler
 */
@Slf4j
public class DefExcelReaderHandler<T> extends AbsExcelReaderHandler<T> implements ExcelReaderHandler {
    /**
     * Excel日期从1900年1月1日开始
     */
    private final LocalDateTime excelEpoch = LocalDateTime.of(1900, 1, 1, 0, 0);

    public DefExcelReaderHandler(Class<T> dataType) {
        super(dataType);
    }

    @Override
    protected T handlerRow(Integer row, Integer column, String value) {
        try {
            return dataType.newInstance();
        }catch (Exception e){
            throw new RuntimeException("SaxCellHandler构建返回对象失败",e);
        }
    }

    @Override
    protected void handlerColumn(T recordData, Integer row, Integer column, String value) {
        try {
            Field field = fieldMap.get(column);
            if (field.getType().equals(String.class)) {
                field.set(recordData, value);
            } else if (field.getType().equals(Integer.class)) {
                field.set(recordData, Integer.valueOf(value));
            } else if (field.getType().equals(Double.class)) {
                field.set(recordData, Double.valueOf(value));
            } else if (field.getType().equals(Date.class)) {
                LocalDateTime actualDate = excelEpoch.plusDays(Long.parseLong(value) - 1);
                Date date = DateUtils.localDateTimeToDate(actualDate);
                field.set(recordData, date);
            } else if (field.getType().equals(LocalDateTime.class)) {
                LocalDateTime actualDate = excelEpoch.plusDays(Long.parseLong(value) - 1);
                field.set(recordData, actualDate);
            } else if (field.getType().equals(LocalDate.class)) {
                LocalDateTime actualDate = excelEpoch.plusDays(Long.parseLong(value) - 1);
                field.set(recordData, actualDate.toLocalDate());
            }
        } catch (Exception e) {
            log.error("反射set调用错误",e);
        }
    }

}
